package org.hank.wanandroid.ui.fragment

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.widget.NestedScrollView
import cn.bingoogolapple.bgabanner.BGABanner
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_home.view.*
import org.hank.commom.base.BaseBindingFragment
import org.hank.commom.listener.ReloadListener
import org.hank.wanandroid.R
import org.hank.wanandroid.bean.HomeBannerBean
import org.hank.wanandroid.bean.PageArticleBean
import org.hank.wanandroid.constants.Constants
import org.hank.wanandroid.databinding.FragmentHomeBinding
import org.hank.wanandroid.http.HttpConfig
import org.hank.wanandroid.listener.OnArticleRecyclerListener
import org.hank.wanandroid.ui.SearchActivity
import org.hank.wanandroid.ui.WebActivity
import org.hank.wanandroid.ui.widget.ArticleRecycleWidget
import org.hank.wanandroid.viewmodel.HomePageViewModel


//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2021/4/15 17:04
 *描述:
 */
class HomePageFragment : BaseBindingFragment<FragmentHomeBinding>(R.layout.fragment_home),
    ReloadListener,
    BGABanner.Delegate<ImageView, String>, OnArticleRecyclerListener {
    lateinit var banner: BGABanner
    var data: MutableList<HomeBannerBean> = ArrayList()
    lateinit var refresh: SmartRefreshLayout
    lateinit var curPage: PageArticleBean
    var CurPage = 0
    var articleRecyclerFragment = ArticleRecycleWidget(this)
    private val homePageViewModel by getViewModel(HomePageViewModel::class.java) {
        bannerLive.observe(it) {
            if (it.size == 0)
                loadingTip.showEmpty()
            else
                loadingTip.dismiss()
            validateBanner(it)
            refresh.finishRefresh()
        }
        articleLive.observe(it) {
            validateArticle(it)
            dismissLoadRefresh()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            rlSearch.elevation = 10f
            llRadius.elevation = 20f
        }

        banner = view.banner_home
        refresh = smartrefresh_home
        dataBinding?.setAdapter { banner, itemView, model, position ->
            Glide.with(itemView!!.context)
                .load(model)
                .apply(
                    RequestOptions()
                        //默认图片
                        //                            .placeholder(R.drawable.holder)
                        //                            .error(R.drawable.holder)
                        .dontAnimate()
                        .centerCrop()
                )
                .into(itemView as ImageView)
        }
        dataBinding?.delegate = this
//        banner.setDelegate(this)

        reload()
        loadingTip.loading()
        loadingTip.setReloadListener(this)
        refresh.setOnRefreshListener {
            articleRecyclerFragment.notifyReload()
            reload()
        }
        refresh.setOnLoadMoreListener {
            //加载更多不能超过最大页数
            if (CurPage != curPage.pageCount - 1) {
                homePageViewModel.getArticle(CurPage)
            } else {
                articleRecyclerFragment.validateData(null)
                refresh.finishLoadMore()
            }
        }
        //设置滚动时 搜索栏的透明度
        nestedView.setOnScrollChangeListener(
            NestedScrollView.OnScrollChangeListener
            { _, _, scrollY, _, _ ->
                val alpha = if (scrollY > 0) {
                    ivSearch.isEnabled = true
                    scrollY.toFloat() / (300).toFloat()
                } else {
                    ivSearch.isEnabled = false
                    0f
                }
                rlSearch.alpha = alpha
            })
        var ft = childFragmentManager.beginTransaction()
        ft.add(R.id.frame_home_article, articleRecyclerFragment)
        ft.commit()
        dataBinding.ivSearch.setOnClickListener {
            startActivity(Intent(context,SearchActivity::class.java))
            activity?.overridePendingTransition(0, 0)
        }
        super.onViewCreated(view, savedInstanceState)
    }

    fun validateBanner(data: MutableList<HomeBannerBean>) {
        this.data = data

        var arrayPic: MutableList<String> = ArrayList()
        var arrayDescript: MutableList<String> = ArrayList()
        for (item in data) {
            arrayDescript.add(item.desc)
            arrayPic.add(item.imagePath)
        }
        //data 在xml是特殊的无法使用databinding
        banner.setData(arrayPic, null)
    }

    fun validateArticle(pageArticleBean: PageArticleBean) {
        this.curPage = pageArticleBean
        articleRecyclerFragment.validateData(pageArticleBean.datas)
    }

    override fun reload() {
        CurPage = 0
        getData()
    }

    fun getData() {
        homePageViewModel.getBanner()
        homePageViewModel.getArticle(CurPage)
    }

    override fun onBannerItemClick(
        banner: BGABanner?,
        itemView: ImageView?,
        model: String?,
        position: Int
    ) {
        var intent = Intent(context, WebActivity::class.java)
        var bundle = Bundle()
        var link =
            if (data[position].url.startsWith("/"))
                HttpConfig.BASE_URL_MAP + data[position].url
            else
                data[position].url
        bundle.putString(Constants.WEB_URL, link)
        bundle.putString(Constants.WEB_TITLE, data[position].title)
        intent.putExtras(bundle)
        startActivity(intent)
    }

    fun dismissLoadRefresh() {
        refresh.finishLoadMore()
        refresh.finishRefresh()
        CurPage = CurPage.plus(1)
    }

    override fun onReload() {
        reload()
    }

    override fun showToast(msg: String) {
        super.showToast(msg)
        dismissLoadRefresh()
        articleRecyclerFragment.validateData(null)
        loadingTip.showInternetError()
    }
}